<template>
  <div class="form" @click.stop.prevent="">
    <div class="form_head l-f l-row-sb">
      <div class="form_head_left l-f">
        <img class="form_head_left_logo" src="@/assets/logo.svg" />
        <div class="form_head_left_info">
          <p class="form_head_left_info_name">Tether Gold</p>
          <p class="form_head_left_info_desc">{{ COIN.name }}USDT</p>
        </div>
      </div>
      <div class="form_head_right">
        <p class="form_head_right_money">${{ dayMarket.close }}</p>
        <div class="l-f l-row-end">
          <img
            class="form_head_right_icon"
            :src="isUp(dayMarket.change) ? IconUp : IconDown"
            alt=""
          />
          <p
            class="form_head_right_rate"
            :class="isUp(dayMarket.change) ? 'color-green' : 'color-red'"
          >
            {{ dayMarket.change }} %
          </p>
        </div>
      </div>
    </div>
    <div class="form_line"></div>
    <div class="form_content">
      <p class="form_content_title">{{ $t("account.time") }}</p>
      <!-- 结果 -->
      <template v-if="showResult">
        <div class="countdown">
          <div v-if="countDownTime > 0" class="l-f">
            <div class="countdown_left">
                <p class="countdown_left_time">{{countDownTime}} S</p>
                <p class="countdown_left_ror">{{$t('account.ror')}}: {{resultObj.profitRatio}} %</p>
            </div>
            <div class="countdown_progress l-f1">
              <div class="countdown_progress_inner" :style="{
                width: progress + '%'
              }"></div>
            </div>
          </div>
          <div v-else class="countdown_info l-f l-row-c">
            <p class="countdown_info_value" :class="resultObj.profitResult > 0 ? 'color-green' : 'color-red'">{{resultObj.profitResult > 0 ? '+' : '-'}}$ {{resultObj.factProfits}}</p>
          </div>
        </div>
        <div class="result l-f l-wrap">
          <div class="result_item l-f l-column l-row-c">
            <p class="result_item_label">{{$t('account.amount')}}</p>
            <p class="result_item_value">$ {{resultObj.u}}</p>
          </div>
          <div class="result_item l-f l-column l-row-c">
            <p class="result_item_label">{{$t('account.openPrice')}}</p>
            <p class="result_item_value">{{resultObj.openPrice}}</p>
          </div>
          <div class="result_item l-f l-column l-row-c">
            <p class="result_item_label">{{$t('account.fee')}}</p>
            <p class="result_item_value">$ {{numberFormat(resultObj.fee)}}</p>
          </div>
          <div class="result_item l-f l-column l-row-c">
            <p class="result_item_label">{{$t('account.expected')}}</p>
            <p class="result_item_value">{{ resultObj.factProfits > 0 ? ((resultObj.profitResult > 0 ? '+' : '-') + '$' + resultObj.factProfits) : expectFactProfits()}}</p>
          </div>
          <div class="result_item l-f l-column l-row-c">
            <p class="result_item_label">{{$t('account.currentPrice')}}</p>
            <p class="result_item_value">$ {{ resultObj.closePrice > 0 ? resultObj.closePrice :  dayMarket.close}}</p>
          </div>
          <div class="result_item l-f l-column l-row-c">
            <p class="result_item_label">{{$t('option.type')}}</p>
            <p class="result_item_value">{{resultObj.type == 1 ? $t('option.buyLong') : $t('option.buyShort')}}</p>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form_content_list">
          <flicking
            :key="key"
            ref="flickingRef"
            :options="flickingOptions"
            :viewportTag="'div'"
            :cameraTag="'div'"
            :cameraClass="''"
          >
            <li
              @click="onSelect(index)"
              class="form_content_list_item l-f l-column l-row-c"
              :class="
                currentIndex === index ? 'form_content_list_item-active' : ''
              "
              v-for="(item, index) in listData"
              :key="index"
            >
              <p class="form_content_list_item_label">{{ item.seconds }} s</p>
              <p class="form_content_list_item_rate">
                Ror: {{ Number(item.profit_ratio) }}%
              </p>
            </li>
          </flicking>
        </div>
        <div class="form_content_fee l-f l-row-sb">
          <p class="form_content_fee_title">
            {{ $t("option.transactionFees") }}
          </p>
          <p class="form_content_fee_money l-text-gradient">$ {{numberFormat(feeComputed,4)}}</p>
        </div>
        <NumberInput v-model="number" />
        <div class="l-f l-row-sb form_content_balance">
          <p class="form_content_balance_label">
            {{ $t("account.availableBalance") }}
          </p>
          <p class="form_content_balance_value l-text-gradient">
            {{balanceTotal.toFixed(4)}} USDT
          </p>
        </div>
      </template>
    </div>
    <a-button
      v-if="showResult"
      @click="onConfirm"
      type="primary"
      class="form_confirm"
      >{{ $t("account.confirm") }}</a-button
    >
    <template v-else>
      <a-button
        @click="onSubmit(0)"
        type="primary"
        class="form_confirm"
        v-if="isMobile"
        >{{ $t("account.confirm") }}</a-button
      >
      <div v-else class="form_bottom l-f l-row-sb">
        <a-button
          @click="onSubmit(1)"
          class="form_bottom_btn bg-green"
          type="primary"
          >{{ $t("option.buyLong") }}</a-button
        >
        <a-button
          @click="onSubmit(2)"
          class="form_bottom_btn bg-red"
          type="primary"
          >{{ $t("option.buyShort") }}</a-button
        >
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted,onUnmounted } from "vue";
import { message } from "ant-design-vue";
import { useI18n } from "vue-i18n";
import { useMainStore } from "@/store";
import { isUp, throttle, numberFormat } from "@/utils/index.js";
import { COIN } from "@/common/index.js";
import { getSecondsListApi, getSecondsDetailApi, getSecondsFeeApi } from "@/api/tradeApi.js";

import NumberInput from "@/components/numberInput/index.vue";
import Flicking from "@egjs/vue3-flicking";

import IconUp from "@/assets/icons/icon-coin_up.svg";
import IconDown from "@/assets/icons/icon-coin_down.svg";

const emits = defineEmits(["submit","hideResult"]);

const { t } = useI18n();
const mainStore = useMainStore();

const key = ref(0);
const number = ref(0);
const showResult = ref(false)
const resultObj = reactive({
  id: null,
  type: 1,
  status: 1,
  openPrice: 0,
  closePrice: 0,
  u: 0,
  profitResult: 0,
  factProfits: 0,
  profitRatio: 0,
  fee: 0
})
const countDownTime = ref(0)
const timeId = ref(null)
const progress = ref(0)
const oldPrice = ref(0)
const fee = ref(0)
const isGetResult = ref(true)

const dayMarket = computed(() => {
  return mainStore.dayMarket;
});

const isMobile = computed(() => {
  return mainStore.isMobile;
});

const balanceTotal = computed(() => {
    return mainStore.userInfo.balance
})

const feeComputed = computed(() => {
  if(number.value && fee.value) {
    return (fee.value * number.value) / 100
  }
  return 0
})

// 预计盈亏计算
const expectFactProfits = () => {
  let oldClose = parseFloat(oldPrice.value)
  let newClose = parseFloat(dayMarket.value.close)
  // oldClose == newClose ，盈亏为0
  if (oldClose === newClose) {
    return '-$' + parseFloat((resultObj.u *resultObj.profitRatio)/100)
  }
  // 如果购买方向和当前涨跌情况相同,则计算结果为 (number * profit_ratio) / 100
  if ((resultObj.type === 1 && newClose > oldClose) ||
   (resultObj.type === 2 && oldClose > newClose)) {
      return '+$' + parseFloat((resultObj.u * resultObj.profitRatio) / 100)
    } else {
      // 如果购买方向和当前涨跌情况相反,则计算结果为 - amountNum
      return '-$' + parseFloat((resultObj.u *resultObj.profitRatio)/100)
    }
}

watch(
  () => mainStore.isMobile,
  (newVal) => {
    key.value++;
  }
);

const currentIndex = ref(null);
let listData = ref([]);

const flickingRef = ref(null);

const flickingOptions = {
  circular: false,
  bound: true,
  duration: 500,
  defaultIndex: 0,
  horizontal: true,
  moveType: "freeScroll",
};

onMounted(() => {
  getSecondsList();
  getSecondsFee()
});

onUnmounted(() => {
  isGetResult.value = false
})

const getSecondsList = async () => {
  const res = await getSecondsListApi();
  listData.value = res;
};

const onSelect = (index) => {
  currentIndex.value = index;
};

const setResult = (data) => {
  showResult.value = true
  
  resultObj.id = data.id
  resultObj.type = data.type
  resultObj.openPrice = data.open_price
  resultObj.status = data.status
  resultObj.u = data.u
  resultObj.profitResult = data.profit_result
  resultObj.profitRatio = data.profit_ratio
  resultObj.fee = data.fee

  oldPrice.value = parseFloat(data.end_price)

  const currentSecond = listData.value[currentIndex.value]
  countDownTime.value = currentSecond.seconds
  if(timeId.value) {
    clearInterval(timeId.value)
  }
  timeId.value = setInterval(() => {
    countDownTime.value --
    if(countDownTime.value <= 0) {
      clearInterval(timeId.value)
      console.log('获取结果')
      getSecondsDetail()
    }
    // 计算进度百分比
    progress.value = parseInt((currentSecond.seconds - countDownTime.value) / currentSecond.seconds * 100)
  },1000)
}

// 获取交易详情
const getSecondsDetail = async () => {
  const res = await getSecondsDetailApi({
    id: resultObj.id
  })
  if (res && res.status === 3) {
      resultObj.factProfits = parseFloat(res.fact_profits)
      resultObj.closePrice = parseFloat(res.end_price)
      resultObj.profitResult = res.profit_result
    } else {
      // 没有平仓继续请求
      if(!isGetResult.value) return
      setTimeout(() => {
        getSecondsDetail()
      }, 2000)
    }
}
// 获取期权手续费
const getSecondsFee = async () => {
  const res = await getSecondsFeeApi()
  fee.value = parseFloat(res)
}

const onConfirm = () => {
  showResult.value = false
  progress.value = 0
  resultObj.id = null
  resultObj.type = 1
  resultObj.status = 1
  resultObj.openPrice = 0
  resultObj.closePrice = 0
  resultObj.u = 0
  resultObj.profitResult = 0
  resultObj.factProfits = 0
  resultObj.profitRatio =  0
}

const onSubmit = throttle((type) => {
  if (currentIndex.value === null) {
    message.warning(t("option.pleaseSelectATimeToProceed"));
    return;
  }
  const currentSecond = listData.value[currentIndex.value];
  let min = parseFloat(currentSecond.min_amount),
    max = parseFloat(currentSecond.max_amount);
  if (number.value < min || number.value > max) {
    message.warning(
      t("option.theValidAmountRangeIsAnd", { min: min, max: max })
    );
    return;
  }
  // 提交时的价
  oldPrice.value = dayMarket.value.close
  emits("submit", {
    number: number.value,
    second: currentSecond.seconds,
    type: type,
  });
}, 3000);

defineExpose({
  setResult
})

</script>

<style lang="scss" scoped>
.form {
  &_head {
    &_left {
      &_logo {
        width: 48px;
        height: 38px;
      }
      &_info {
        margin-left: 15px;
        &_name {
          font-size: 16px;
          font-weight: 400;
          color: #ffffff;
        }
        &_desc {
          font-size: 12px;
          color: #575b66;
        }
      }
    }
    &_right {
      &_money {
        font-size: 16px;
        font-weight: 400;
        color: #ffffff;
      }
      &_icon {
        width: 16px;
        height: 16px;
      }
      &_rate {
        font-size: 12px;
        color: #e8503a;
        font-weight: 400;
      }
    }
  }
  &_line {
    height: 1.5px;
    margin: 30px 0;
    background-color: #b8b8b81a;
  }
  &_content {
    &_title {
      font-size: 16px;
      color: #ffffff;
      font-weight: 500;
    }
    &_list {
      margin-top: 20px;
      &_item {
        background-color: #1e2239;
        border-radius: 12px;
        min-width: 72px;
        height: 72px;
        cursor: pointer;
        margin-right: 16px;
        &_label {
          font-size: 14px;
          color: #ffffff;
          font-weight: 600;
        }
        &_rate {
          font-size: 10px;
          color: #575b66;
          font-weight: 400;
        }
      }
      &_item-active {
        border: 1px solid #6d6050;
        background: #22263d;
      }
    }
    &_fee {
      margin: 20px 0;
      &_title {
        font-size: 14px;
        color: #ffffff;
        opacity: 0.5;
      }
    }
    &_balance {
      margin: 15px 0;
      &_label {
        font-size: 14px;
        color: #fffc;
        opacity: 0.5;
        font-weight: 400;
      }
      &_money {
        font-size: 14px;
        font-weight: 400;
      }
    }
  }
  &_confirm {
    height: 52px;
    width: 100%;
    font-weight: 500;
    margin-top: 20px;
  }
  &_bottom {
    margin-top: 30px;
    gap: 30px;
    &_btn {
      height: 42px;
      font-weight: 500;
      width: 100%;
      color: #ffffff !important;
      font-size: 12px;
    }
  }
}

.countdown {
  background-color:  #1E2239;
  border-radius: 12px;
  margin-top: 16px;
  padding: 16px;
  box-sizing: border-box;
  &_left {
    margin-right: 20px;
    &_time {
      font-size: 14px;
      color: #ffffff;
      font-weight: 700;
    }
    &_ror {
      font-weight: 500;
      font-size: 12px;
      color: #ffffff;
      opacity: .5;
    }
  }
  &_progress {
    background-color: rgba(130, 169, 249, 0.2);
    height: 8px;
    border-radius: 4px;
    overflow: hidden;
    position: relative;
    &_inner {
      background-color: rgb(211, 178, 91);
      width: 0;
      height: 8px;
      position: absolute;
      left: 0;
      transition: width .3s ease-in-out;
    }
  }
  &_info {
    height: 40px;
    &_value {
      font-size: 18px;
      font-weight: 700;
    }
  }
}
.result {
  background-color:  #1E2239;
  border-radius: 12px;
  margin-top: 16px;
  padding: 10px 16px;
  box-sizing: border-box;
  &_item {
    width: 33.333%;
    margin: 5px 0;
    &_label {
      font-size: 10px;
      color: #ffffff;
      opacity: .4;
      font-weight: 500;
    }
    &_value {
      font-size: 14px;
      color: #ffffff;
      font-weight: 700;
      margin-top: 2px;
    }
  }
}

@media only screen and (max-width: 1200px) {
  .form {
    &_line {
      margin: 15px 0;
      height: 1px;
    }
    &_content {
      &_list {
        &_item {
          background-color: #12112c;
        }
      }
    }
  }
  .countdown {
    background-color: #12112d;
  }
  .result {
    background-color: #12112d;
  }
}
</style>